<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { Message, Modal } from '@arco-design/web-vue'
import { getDishById, getDishSpecByDishId } from '@/api/dish'
import { createOrder } from '@/api/order'
import type { Merchant } from '@/api/merchant'
import type { Dish, DishSpec } from '@/api/dish'
import type { Order, OrderItem } from '@/api/order'
import type { ApiResponse } from '@/api/user'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const loading = ref(false)
const submitting = ref(false)
const merchant = ref<Merchant | null>(null)
const userStore = useUserStore()
const cartItems = ref<Array<{
  dishId: number
  dishSpecId?: number
  quantity: number
  dish?: Dish
  spec?: DishSpec
}>>([])

// 收货信息
const deliveryInfo = reactive({
  receiverName: '',
  receiverPhone: '',
  deliveryAddress: '',
  remark: ''
})

// 初始化数据
onMounted(async () => {
  loading.value = true
  try {
    // 初始化用户状态
    if (userStore.isLoggedIn && !userStore.currentUser) {
      await userStore.fetchCurrentUser()
    }
    
    // 从localStorage获取购物车数据
    const merchantIds = Object.keys(localStorage)
      .filter(key => key.startsWith('cart_'))
      .map(key => Number(key.replace('cart_', '')))
    
    if (merchantIds.length === 0) {
      Message.warning('购物车为空')
      router.push('/')
      return
    }
    
    // 目前只支持一个商家的购物车
    const merchantId = merchantIds[0]
    
    // 从localStorage获取商家信息（如果有）
    const merchantInfoStr = localStorage.getItem(`merchant_info_${merchantId}`)
    if (merchantInfoStr) {
      try {
        merchant.value = JSON.parse(merchantInfoStr)
        console.log('从本地存储获取商家信息:', merchant.value)
      } catch (e) {
        console.error('解析商家信息失败:', e)
        // 创建一个基本的商家对象
        merchant.value = {
          id: merchantId,
          username: '',
          name: '商家',
          address: '',
          phone: '',
          description: '',
          image: '',
          businessHours: '',
          deliveryFee: 0,
          minOrderAmount: 0,
          categoryId: 0,
          status: 1
        }
      }
    } else {
      // 创建一个基本的商家对象
      merchant.value = {
        id: merchantId,
        username: '',
        name: '商家',
        address: '',
        phone: '',
        description: '',
        image: '',
        businessHours: '',
        deliveryFee: 0,
        minOrderAmount: 0,
        categoryId: 0,
        status: 1
      }
    }
    
    const cartKey = `cart_${merchantId}`
    const cartData = localStorage.getItem(cartKey)
    
    if (cartData) {
      try {
        const items = JSON.parse(cartData)
        
        // 从localStorage获取菜品详情
        for (const item of items) {
          // 尝试从localStorage获取菜品信息
          const dishInfoStr = localStorage.getItem(`dish_info_${item.dishId}`)
          let dish = null
          
          if (dishInfoStr) {
            try {
              dish = JSON.parse(dishInfoStr)
              console.log(`从本地存储获取菜品信息 ID:${item.dishId}`, dish)
            } catch (e) {
              console.error(`解析菜品信息失败 ID:${item.dishId}:`, e)
            }
          }
          
          // 如果本地没有菜品信息，则尝试从API获取
          if (!dish) {
            try {
              const dishRes = await getDishById(item.dishId)
              if (dishRes.code === 200 && dishRes.data) {
                dish = dishRes.data
                // 保存到localStorage以便下次使用
                localStorage.setItem(`dish_info_${item.dishId}`, JSON.stringify(dish))
              } else {
                console.error('获取菜品信息失败:', dishRes.message)
              }
            } catch (error) {
              console.error(`获取菜品信息失败 ID:${item.dishId}:`, error)
              // 创建一个基本的菜品对象
              dish = {
                id: item.dishId,
                name: `菜品${item.dishId}`,
                price: 0,
                image: '',
                description: '',
                categoryId: 0,
                isSpecial: 0,
                specialPrice: 0,
                isRecommended: 0,
                merchantId: merchantId,
                status: 1
              }
            }
          }
          
          let spec = undefined
          if (item.dishSpecId) {
            // 尝试从localStorage获取规格信息
            const specInfoStr = localStorage.getItem(`spec_info_${item.dishSpecId}`)
            if (specInfoStr) {
              try {
                spec = JSON.parse(specInfoStr)
              } catch (e) {
                console.error(`解析规格信息失败 ID:${item.dishSpecId}:`, e)
              }
            }
            
            // 如果本地没有规格信息，则尝试从API获取
            if (!spec) {
              try {
                const specsRes = await getDishSpecByDishId(item.dishId)
                if (specsRes.code === 200 && specsRes.data) {
                  spec = specsRes.data.find(s => s.id === item.dishSpecId)
                  if (spec) {
                    // 保存到localStorage以便下次使用
                    localStorage.setItem(`spec_info_${item.dishSpecId}`, JSON.stringify(spec))
                  }
                }
              } catch (error) {
                console.error(`获取规格信息失败 ID:${item.dishSpecId}:`, error)
              }
            }
          }
          
          cartItems.value.push({
            ...item,
            dish: dish,
            spec
          })
        }
        
        console.log('成功加载购物车菜品:', cartItems.value)
      } catch (e) {
        console.error('解析购物车数据失败:', e)
        Message.error('加载购物车数据失败')
      }
    }
    
    // 从localStorage获取用户信息
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      try {
        const userInfo = JSON.parse(userInfoStr)
        deliveryInfo.receiverName = userInfo.name || ''
        deliveryInfo.receiverPhone = userInfo.phone || ''
        deliveryInfo.deliveryAddress = userInfo.address || ''
      } catch (e) {
        console.error('解析用户信息失败:', e)
      }
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    Message.error('加载数据失败，请稍后再试')
  } finally {
    loading.value = false
  }
})

// 计算商品总价
const subtotal = computed(() => {
  return cartItems.value.reduce((total, item) => {
    let price = 0
    
    if (item.spec) {
      price = item.spec.price
    } else if (item.dish) {
      price = item.dish.isSpecial ? (item.dish.specialPrice || item.dish.price) : item.dish.price
    }
    
    return total + price * item.quantity
  }, 0)
})

// 配送费
const deliveryFee = computed(() => {
  return merchant.value?.deliveryFee || 0
})

// 计算总价
const totalPrice = computed(() => {
  return subtotal.value + deliveryFee.value
})

// 移除购物车项
const removeCartItem = (index: number) => {
  cartItems.value.splice(index, 1)
  
  // 更新localStorage
  if (merchant.value) {
    const cartKey = `cart_${merchant.value.id}`
    const items = cartItems.value.map(item => ({
      dishId: item.dishId,
      dishSpecId: item.dishSpecId,
      quantity: item.quantity
    }))
    
    if (items.length === 0) {
      localStorage.removeItem(cartKey)
    } else {
      localStorage.setItem(cartKey, JSON.stringify(items))
    }
  }
}

// 更新购物车项数量
const updateCartItemQuantity = (index: number, quantity: number) => {
  if (quantity < 1) return
  
  cartItems.value[index].quantity = quantity
  
  // 更新localStorage
  if (merchant.value) {
    const cartKey = `cart_${merchant.value.id}`
    const items = cartItems.value.map(item => ({
      dishId: item.dishId,
      dishSpecId: item.dishSpecId,
      quantity: item.quantity
    }))
    
    localStorage.setItem(cartKey, JSON.stringify(items))
  }
}

// 清空购物车
const clearCart = () => {
  Modal.confirm({
    title: '确认清空购物车？',
    content: '清空后将无法恢复',
    onOk: () => {
      cartItems.value = []
      
      // 清除localStorage
      if (merchant.value) {
        const cartKey = `cart_${merchant.value.id}`
        localStorage.removeItem(cartKey)
      }
      
      Message.success('购物车已清空')
      router.push('/')
    }
  })
}

// 提交订单
const submitOrder = async () => {
  if (!merchant.value) {
    Message.error('商家信息不存在')
    return
  }
  
  if (cartItems.value.length === 0) {
    Message.warning('购物车为空')
    return
  }
  
  // 验证收货信息
  if (!deliveryInfo.receiverName) {
    Message.warning('请填写收货人姓名')
    return
  }
  
  if (!deliveryInfo.receiverPhone) {
    Message.warning('请填写收货人电话')
    return
  }
  
  if (!deliveryInfo.deliveryAddress) {
    Message.warning('请填写收货地址')
    return
  }
  
  // 检查用户是否已登录
  if (!userStore.isLoggedIn) {
    Modal.confirm({
      title: '请先登录',
      content: '提交订单需要登录账号，是否前往登录页面？',
      onOk: () => {
        // 保存当前页面路径，登录后可以跳回来
        router.push(`/login?redirect=${encodeURIComponent('/cart')}`)
      }
    })
    return
  }
  
  // 保存用户信息到localStorage
  localStorage.setItem('userInfo', JSON.stringify({
    name: deliveryInfo.receiverName,
    phone: deliveryInfo.receiverPhone,
    address: deliveryInfo.deliveryAddress
  }))
  
  // 构建订单数据
  const orderItems: OrderItem[] = cartItems.value.map(item => ({
    dishId: item.dishId,
    dishSpecId: item.dishSpecId,
    quantity: item.quantity
  }))
  
  const orderData = {
    userId: userStore.currentUser?.id || 0, // 使用当前登录用户的ID
    merchantId: merchant.value.id,
    deliveryAddress: deliveryInfo.deliveryAddress,
    receiverName: deliveryInfo.receiverName,
    receiverPhone: deliveryInfo.receiverPhone,
    remark: deliveryInfo.remark,
    orderItems
  }
  
  submitting.value = true
  try {
    // 创建订单
    const orderRes = await createOrder(orderData)
    if (orderRes.code === 200 && orderRes.data) {
      // 清空购物车
      if (merchant.value) {
        const cartKey = `cart_${merchant.value.id}`
        localStorage.removeItem(cartKey)
      }
      
      Message.success('订单提交成功')
      
      // 跳转到订单页面
      router.push('/order')
    } else {
      throw new Error(orderRes.message || '创建订单失败')
    }
  } catch (error) {
    console.error('提交订单失败:', error)
    Message.error('提交订单失败，请稍后再试')
  } finally {
    submitting.value = false
  }
}

// 返回商家页面
const goBackToMerchant = () => {
  if (merchant.value) {
    router.push(`/merchant/${merchant.value.id}`)
  } else {
    router.push('/')
  }
}
</script>

<template>
  <div class="cart-container">
    <a-spin :loading="loading" tip="加载中...">
      <!-- 标题栏 -->
      <div class="cart-header">
        <a-button shape="circle" @click="goBackToMerchant">
          <template #icon><icon-left /></template>
        </a-button>
        <h2>购物车</h2>
        <a-button type="text" status="danger" @click="clearCart">清空</a-button>
      </div>

      <!-- 商家信息 -->
      <div v-if="merchant" class="merchant-info">
        <a-avatar>
          <template #icon><icon-shop /></template>
        </a-avatar>
        <div class="merchant-name">{{ merchant.name }}</div>
      </div>

      <!-- 购物车列表 -->
      <div class="cart-list">
        <a-empty v-if="cartItems.length === 0" description="购物车为空" />
        <div v-else v-for="(item, index) in cartItems" :key="index" class="cart-item">
          <div class="item-image">
            <img :src="'https://materials.cdn.bcebos.com/images/39275436/26649005146a34c5ba54ba695f238091.jpeg'" alt="菜品图片" />
          </div>
          <div class="item-info">
            <h3>{{ item.dish?.name }}</h3>
            <p v-if="item.spec" class="item-spec">规格：{{ item.spec.name }}</p>
            <div class="item-price">
              <span>¥{{ 
                item.spec 
                  ? item.spec.price 
                  : (item.dish?.isSpecial 
                      ? (item.dish?.specialPrice || item.dish?.price) 
                      : item.dish?.price) || 0 
              }}</span>
            </div>
          </div>
          <div class="item-actions">
            <a-button
              shape="circle"
              size="mini"
              @click="updateCartItemQuantity(index, item.quantity - 1)"
              :disabled="item.quantity <= 1"
            >
              <template #icon><icon-minus /></template>
            </a-button>
            <span class="item-quantity">{{ item.quantity }}</span>
            <a-button
              shape="circle"
              size="mini"
              @click="updateCartItemQuantity(index, item.quantity + 1)"
            >
              <template #icon><icon-plus /></template>
            </a-button>
            <a-button
              shape="circle"
              size="mini"
              status="danger"
              @click="removeCartItem(index)"
            >
              <template #icon><icon-delete /></template>
            </a-button>
          </div>
        </div>
      </div>

      <!-- 收货信息 -->
      <div class="delivery-info">
        <h3>收货信息</h3>
        <a-form :model="deliveryInfo" layout="vertical">
          <a-form-item field="receiverName" label="收货人">
            <a-input v-model="deliveryInfo.receiverName" placeholder="请输入收货人姓名" />
          </a-form-item>
          <a-form-item field="receiverPhone" label="联系电话">
            <a-input v-model="deliveryInfo.receiverPhone" placeholder="请输入联系电话" />
          </a-form-item>
          <a-form-item field="deliveryAddress" label="收货地址">
            <a-input v-model="deliveryInfo.deliveryAddress" placeholder="请输入收货地址" />
          </a-form-item>
          <a-form-item field="remark" label="备注">
            <a-textarea v-model="deliveryInfo.remark" placeholder="请输入备注信息" />
          </a-form-item>
        </a-form>
      </div>

      <!-- 价格信息 -->
      <div class="price-info">
        <div class="price-item">
          <span>商品金额</span>
          <span>¥{{ subtotal.toFixed(2) }}</span>
        </div>
        <div class="price-item">
          <span>配送费</span>
          <span>¥{{ deliveryFee.toFixed(2) }}</span>
        </div>
        <div class="price-total">
          <span>合计</span>
          <span>¥{{ totalPrice.toFixed(2) }}</span>
        </div>
      </div>

      <!-- 提交订单 -->
      <div class="submit-order">
        <a-button
          type="primary"
          long
          size="large"
          :loading="submitting"
          :disabled="cartItems.length === 0"
          @click="submitOrder"
        >
          {{ cartItems.length === 0 ? '购物车为空' : '提交订单' }}
        </a-button>
      </div>
    </a-spin>
  </div>
</template>

<style scoped>
.cart-container {
  padding: 0 0 80px 0;
}

.cart-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid var(--color-border);
}

.cart-header h2 {
  margin: 0;
}

.merchant-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border-bottom: 1px solid var(--color-border);
}

.merchant-name {
  font-size: 16px;
  font-weight: bold;
}

.cart-list {
  padding: 16px;
}

.cart-item {
  display: flex;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid var(--color-border);
}

.item-image {
  width: 80px;
  height: 80px;
  overflow: hidden;
  border-radius: 4px;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
}

.item-info h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.item-spec {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: var(--color-text-3);
}

.item-price {
  font-size: 16px;
  font-weight: bold;
  color: #ff4d4f;
}

.item-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.item-quantity {
  width: 24px;
  text-align: center;
}

.delivery-info {
  padding: 16px;
  border-top: 1px solid var(--color-border);
}

.delivery-info h3 {
  margin: 0 0 16px 0;
}

.price-info {
  padding: 16px;
  border-top: 1px solid var(--color-border);
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.price-total {
  display: flex;
  justify-content: space-between;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--color-border);
  font-size: 18px;
  font-weight: bold;
}

.price-total span:last-child {
  color: #ff4d4f;
}

.submit-order {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background-color: var(--color-bg-2);
  border-top: 1px solid var(--color-border);
  z-index: 10;
}
</style> 